package com.liu.lsm.sys.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.liu.lsm.common.LoginDto;
import com.liu.lsm.common.Result;
import com.liu.lsm.sys.entity.User;
import com.liu.lsm.sys.service.UserService;
import com.liu.lsm.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
public class AccountController {


    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response){

        /**
         * Assert.notNull(user, "用户不存在");
         * 判断传进来的参数值是否不为空值，
         * 如果为空就抛出异常throw new IllegalArgumentException(msg)，
         * 代码如果不捕捉处理这个异常，
         * 代码不往下执行，不为空代码继续向下执行*/
        User user = userService.selectByUsername(loginDto.getUsername());
        Assert.notNull(user, "用户不存在");


        String p = SecureUtil.md5(loginDto.getPassword());
        if(!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))){
            return Result.fail("密码不正确");
        }
        //生成jwt
        String jwt = jwtUtils.generateToken(user.getId());

        //把jwt放入response中，传送会客户端
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .map()
        );

        //如何将shiro框架插入？
        //1.引入shiro-redis 并且在yml中进行配置
        //2.重写AuthenticatingFilter，在wen
        //3.重写AuthorizingRealm



    }


    /**
     * 登出请求处理
     * 权限存在问题，
     */
    @GetMapping("/logout")
  /*  @RequiresAuthentication*/
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ("退出成功");
    }
}
